import 'package:lighthouse/index.dart';

class FilterRightPage extends StatefulWidget with FilterPopupBaseWidget {
  static final GlobalKey<_FilterRightState> _globalKey =
      GlobalKey<_FilterRightState>();

  Offset offsetLT;
  FilterItemData itemData;
  SelectCallback onSelect;
  DismissCallback onDismiss;

  FilterRightPage(
      {required this.itemData,
      required this.onSelect,
      required this.onDismiss,
      this.offsetLT = Offset.zero})
      : super(key: _globalKey);

  @override
  _FilterRightState createState() => _FilterRightState();

  @override
  dismiss() {
    _FilterRightState? state = _globalKey.currentState;
    state?.dismiss();
  }
}

class _FilterRightState extends State<FilterRightPage>
    with SingleTickerProviderStateMixin {
  late FilterItemData _itemData;

  late Animation<Offset> _animation;
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    //对象深拷贝
    _itemData = FilterItemData.fromJson(widget.itemData.toJson());
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 200),
    );
    _animation = Tween<Offset>(begin: const Offset(2, 0), end: Offset.zero)
        .animate(_controller);
    _controller.forward();
  }

  dismiss() {
    widget.onDismiss();
    _controller.reverse();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> slivers = [];
    for (FilterItemData filterItemData in _itemData.children!) {
      slivers.add(
        SliverToBoxAdapter(
          child: GestureDetector(
            child: SizedBox(
              height: 50,
              child: Row(
                children: [
                  Container(
                    margin: EdgeInsets.only(right: 8),
                    height: 15,
                    width: 3,
                    decoration: BoxDecoration(
                      color: Theme.of(context).primaryColor,
                      borderRadius:
                          BorderRadius.all(const Radius.circular(1.5)),
                    ),
                  ),
                  Expanded(
                    child: Text(
                      filterItemData.name,
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                  ),
                  filterItemData.open
                      ? const Icon(Icons.keyboard_arrow_up)
                      : const Icon(Icons.keyboard_arrow_down)
                ],
              ),
            ),
            onTap: () {
              setState(() {
                filterItemData.open = !filterItemData.open;
                // eventBus.fire(AnimationEvent(
                //     _itemData.children!.indexOf(filterItemData),
                //     filterItemData.open));
              });
              widget
                  .itemData
                  .children![_itemData.children!.indexOf(filterItemData)]
                  .open = filterItemData.open;
            },
          ),
        ),
      );
      // filterItemData.open &&
      if (filterItemData.open && filterItemData.children != null) {
        slivers.add(_GridWidget(
          index: _itemData.children!.indexOf(filterItemData),
          itemData: filterItemData,
          onPressed: (int index) {
            FilterItemData itemData = filterItemData.children![index];
            if (filterItemData.radio) {
              //单选
              if (!itemData.isSelect()) {
                setState(() {
                  itemData.setSelect(true);
                  for (FilterItemData mItemData in _itemData.children!) {
                    if (mItemData.code == filterItemData.code) {
                      //将其它单选按钮设置为false
                      for (FilterItemData childItemData
                          in mItemData.children!) {
                        childItemData
                            .setSelect(childItemData.value == itemData.value);
                      }
                    }
                  }
                });
              }
            } else {
              //多选
              setState(() {
                itemData.setSelect(!itemData.isSelect());
                for (FilterItemData mItemData in _itemData.children!) {
                  if (mItemData.code == filterItemData.code) {
                    for (FilterItemData childItemData in mItemData.children!) {
                      if (childItemData.value == itemData.value) {
                        childItemData.setSelect(itemData.isSelect());
                      }
                    }
                  }
                }
              });
            }
          },
        ));
      }
    }

    return GlobalStyle(
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Container(
          padding: EdgeInsets.only(
              left: widget.offsetLT.dx, top: widget.offsetLT.dy),
          child: SlideTransition(
            position: _animation,
            child: GestureDetector(
              onTap: () {
                //阻断内容部分点击关闭效果
              },
              child: Container(
                color: Theme.of(context).colorScheme.background,
                child: SafeArea(
                    child: Padding(
                  padding: EdgeInsets.only(left: 16, right: 16,top: 8,bottom: 8),
                  child: Column(children: [
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        "筛选",
                        style: Theme.of(context)
                            .textTheme
                            .titleMedium
                            ?.copyWith(fontWeight: FontWeight.bold),
                      ),
                    ),
                    Expanded(
                        child: CustomScrollView(
                      slivers: slivers,
                    )),
                    Row(
                      children: [
                        Expanded(
                          child: CommonButton.outlinedButton(context,
                              text: "取消", onPressed: () {
                            //还原选中数据
                            filterPop(context);
                          }),
                        ),
                        const SizedBox(
                          width: 20,
                        ),
                        Expanded(
                          child: CommonButton.elevatedButton(context,
                              text: "确定", onPressed: () {
                            widget.onSelect(_itemData);
                            filterPop(context);
                          }),
                        ),
                      ],
                    ),
                  ]),
                )),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class _GridWidget extends StatefulWidget {
  late FilterItemData itemData;
  void Function(int index)? onPressed;
  int index;

  _GridWidget(
      {Key? key, required this.index, required this.itemData, this.onPressed})
      : super(key: key);

  static _GridWidgetState? of(BuildContext context) =>
      context.findAncestorStateOfType<_GridWidgetState>();

  @override
  State<_GridWidget> createState() => _GridWidgetState();
}

class _GridWidgetState extends State<_GridWidget>
    with SingleTickerProviderStateMixin {
  late Animation<Offset> _animation;
  late AnimationController _controller;

  // late StreamSubscription loginSubscription;

  @override
  void initState() {
    super.initState();
    //对象深拷贝
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 100),
    );
    _animation = Tween<Offset>(begin: const Offset(0, -1), end: Offset.zero)
        .animate(_controller);
    if (widget.itemData.open) {
      show();
    } else {
      dismiss();
    }
    // loginSubscription = eventBus.on<AnimationEvent>().listen((event) {
    //   if (widget.index == event.index) {
    //     if (event.show) {
    //       show();
    //     } else {
    //       dismiss();
    //     }
    //   }
    // });
  }

  @override
  void dispose() {
    super.dispose();
    //取消订阅
    // loginSubscription.cancel();
    _controller.dispose();
  }

  show() {
    _controller.forward();
  }

  dismiss() {
    // widget.onDismiss();
    _controller.reverse();
  }

  @override
  Widget build(BuildContext context) {
    final textScaleFactor = Global.textScaleFactor(context);
    return SliverToBoxAdapter(
      child: ClipRect(
        child: SlideTransition(
          position: _animation,
          child: GridView.builder(
            shrinkWrap: true,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 4.0,
              crossAxisSpacing: 4.0,
              childAspectRatio: 2.0 / textScaleFactor,
            ),
            itemBuilder: (BuildContext context, int index) {
              FilterItemData itemData = widget.itemData.children![index];
              ThemeData theme = Theme.of(context);

              return Stack(
                children: [
                  Positioned(
                    right: 0,
                    bottom: 0,
                    top: 0,
                    left: 0,
                    child: OutlinedButton(
                      style: OutlinedButton.styleFrom(
                        // padding: const EdgeInsets.all(14),
                        side: BorderSide(
                          width: 1,
                          color: itemData.isSelect()
                              ? theme.primaryColor
                              : const Color(0xFFD1D1D1),
                        ),
                      ),
                      child: Text(
                        itemData.name,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        textAlign: TextAlign.center,
                        style: theme.textTheme.bodySmall?.copyWith(
                            color: itemData.isSelect()
                                ? theme.primaryColor
                                : null),
                      ),
                      onPressed: () {
                        if (widget.onPressed != null) {
                          widget.onPressed!(index);
                        }
                      },
                    ),
                  ),
                  itemData.isSelect()
                      ? const Positioned(
                          right: 0,
                          bottom: 0,
                          child: Image(
                              image: AssetImage("images/filter_checked.png"),
                              fit: BoxFit.fill))
                      : Container()
                  // filter_checked
                ],
              );
            },
            itemCount: widget.itemData.children!.length,
          ),
        ),
      ),
    );
  }
}